﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace DotNetRepository
{
    public class ManyToManyEntityEnumeration<TEntity,TManyToManyEntity>  : IEntityEnumeration<TEntity>
        where TEntity : class, IEntity
        where TManyToManyEntity : class, IEntity, new()
    {

        private readonly IEntityEnumeration<TManyToManyEntity> _innerEnumeration;
        private readonly Func<TManyToManyEntity, TEntity> _getEntity;
        private readonly Func<TManyToManyEntity, Guid> _getEntityID;

        public ManyToManyEntityEnumeration(
            ManyToManyEntityEnumerationArgs<TEntity,TManyToManyEntity> args)
        {
            _innerEnumeration = args.InnerEnumeration;
            _getEntity = args.GetEntity;
            _getEntityID = args.GetEntityID;
        }

        public IEnumerator<TEntity> GetEnumerator()
        {
            return _innerEnumeration.Select(manyToMany => _getEntity(manyToMany)).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void OnEntityUpdated(IEntity entity)
        {
            var manyToMany = entity as TManyToManyEntity;
            if (manyToMany != null)
                _innerEnumeration.OnEntityUpdated(manyToMany);
        }

        public void OnEntityDeleted(Guid entityID)
        {
            _innerEnumeration.OnEntityDeleted(entityID);
        }

        public TEntity this[Guid id]
        {
            get { return _innerEnumeration.Where(i => _getEntityID(i) == id).Select(i => _getEntity(i)).FirstOrDefault(); }
        }

        public int RecordCount
        {
            get { return _innerEnumeration.RecordCount; }
        }
    }
}
